<?php

namespace Usap\Model\Admin;

use Usap\Model\BaseModel;
use Usap\Service\Service;

class AdminModel extends BaseModel
{

    //数据源配置
    public function _initialize()
    {
        $this->connection = C('db_pool.admin');
        $this->trueTableName = 'admin';
    }

    public $error = '';

    /**
     * 登录验证
     */
    public function login($username, $password, $login_type = 0)
    {
        $times_db = D("Usap/Admin/Times");

        //用户名如果是手机号的话
        if (checkPhoneNum($username)) {
            //查询帐号
            $r = $this->where(array('mobile' => $username))->find();
        } else {
            //查询帐号
            $r = $this->where(array('username' => $username))->find();
        }
        if (empty($r)) {
            $this->error = '管理员不存在';
            return false;
        }
        $password = md5(md5($password) . $r['encrypt']);
        if ($r['password'] != $password) {

            $this->error = "您当前输入密码错误！";
            return false;
        }
        $this->where(array('userid' => $r['userid']))->save(array('lastloginip' => $ip, 'lastlogintime' => time()));
        //登录日志
        D("Usap/Admin/AdminLog")->add(array(
            'userid' => $r['userid'],
            'username' => $username,
            'httpuseragent' => $_SERVER['HTTP_USER_AGENT'],
            'ip' => get_client_ip(0, true),
            'time' => date('Y-m-d H:i:s'),
            'type' => 'login',
            'sessionid' => session_id(),
        ));
        session('userid', $r['userid']);//登录用户ID(后端)
        session('relationuid', $r['relationuid']);//如果是站长身份，有一个特定的关联前端用户ID(前端)
        session('roleid', $r['roleid']);//角色ID
        cookie('username', $username);
        cookie('userid', $r['userid']);

        //@TODO 单点登录的问题考虑其他机制....
        S('SESSION_ID_' . $r['userid'], session_id());  //单点登录用
        return true;
    }

    /**
     * 获取用户信息
     */
    public function getUserInfo($userid)
    {

        $admin_role_db = D("Usap/Admin/Role");
        $info = $this->field('password, encrypt', true)->where(array('userid' => $userid))->find();
        if ($info) $info['rolename'] = $admin_role_db->getRoleName($info['roleid']);    //获取角色名称
        return $info;
    }


    /**
     * 校验密码
     * @param unknown $userid
     * @param unknown $input_pwd 没有经过MD5加密的
     */
    public function verifyPassword($userid, $input_pwd)
    {

        $info = $this->where("userid='$userid'")->find();
        if (empty($info)) {
            return false;
        }
        $input_pwd = password($input_pwd, $info['encrypt']);
        if ($input_pwd != $info['password']) {
            return false;
        }
        return true;
    }


    /**
     * 修改密码
     * @param int $userid
     * @param string $password 没有经过md5加密
     * @param string $is_modified
     * @return boolean|Ambigous <boolean, unknown>
     */
    public function editPassword($userid, $old_password, $password, $is_modified = '')
    {

        if ($userid < 1) return false;

        $info = $this->where("userid='$userid'")->find();
        if (empty($info)) {

            $this->error = "提交信息有误，请刷新后重试";
            return false;
        }

        $verify_result = $this->verifyPassword($userid, $old_password);
        if (!$verify_result) {
            $this->error = "原密码有误";
            return false;
        }

        if ($info['relationuid']) {

            $user_service = Service::instance()->find('account', 'user');//前端用户修改密码
            $user_info = $user_service->getInfoByID($info['relationuid'], array('reg_time'));
            if (empty($user_info)) {

                $this->error = "账户信息有误";
                return false;
            }

            $edit_result = $user_service->modifyLoginPwd($info['relationuid'], md5($old_password), md5($password));
            if ($edit_result['code'] != '0000') {

                $this->error = $edit_result['msg'];
                return false;
            }
            return true;
        } else {
            $passwordinfo = password($password);
        }

        if (!empty($is_modified)) {
            $passwordinfo['is_modified'] = $is_modified;
        }
        $opt_result = $this->where(array('userid' => $userid))->data($passwordinfo)->save();
        if (!$opt_result) {
            $this->error = '系统异常，修改失败';
            return false;
        }
        return true;
    }

}
